#include <X11/Xlib.h>
#include <stdio.h>
#include <stdlib.h>
#include "fl.h"

#define WIDTH 800
#define HEIGHT 600

typedef struct {
  Display* display;
  Window   window;
  GC       gc;
  Pixmap   pixmap;
} xobject;

void init(xobject* xobj) {
  int screen, depth;
  unsigned long black,white;
  Display* dis;
  Window win, root_win;
  GC gc;

  dis = XOpenDisplay((char *)0);
  screen=DefaultScreen(dis);
  black=BlackPixel(dis, screen);
  white=WhitePixel(dis, screen);
  root_win = DefaultRootWindow(dis);
  win=XCreateSimpleWindow(dis, root_win, 0, 0,	
			  800, 600, 5, black, white);
  XSetStandardProperties(dis, win, "Flx", "Flx", None, NULL, 0, NULL);
  XSelectInput(dis, win, ExposureMask | KeyPressMask);
  gc=XCreateGC(dis, win, 0,0);
  XSetBackground(dis, gc, white);
  XSetForeground(dis, gc, black);
  
  xobj->display = dis;
  xobj->window = win;
  xobj->gc = gc;
  XMapWindow(dis, win);

  depth = DefaultDepth(dis, screen);
  xobj->pixmap = XCreatePixmap(dis, root_win, WIDTH, HEIGHT, depth);
  XSetForeground(dis, gc, white);
  XFillRectangle(dis, xobj->pixmap, gc, 0, 0, WIDTH, HEIGHT);
  XSetForeground(dis, gc, black);
}

void draw_point(fl_t* fl, double x, double y) {
  xobject* xobj = (xobject*)fl->display_obj;
  XDrawPoint(xobj->display,
	     xobj->pixmap,
	     xobj->gc,
	     (int)x, (int)y);
}

int main(int argc, char** argv)
{
  fl_t fl;
  xobject xobj;
  XEvent event;
  KeySym key;
  char text[255];	

  if(argc != 2) {
    printf("Usage: flx filename\n");
    exit(0);
  }

  init(&xobj);
  fl.draw_point = draw_point;
  fl.display_obj = &xobj;
  fl_main(&fl, argv[1]);

  for(;;) {
    XNextEvent(xobj.display, &event);
    if (event.type == Expose && event.xexpose.count == 0) {
      XCopyArea(xobj.display,
		xobj.pixmap,
		xobj.window,
		xobj.gc,
		0,0,
		WIDTH,HEIGHT,
		0,0);
    }
    else if (event.type==KeyPress&&
		    XLookupString(&event.xkey,text,255,&key,0)==1) {
      if (text[0]=='q') {
	XFreeGC(xobj.display, xobj.gc);
	XFreePixmap(xobj.display, xobj.pixmap);
	XDestroyWindow(xobj.display, xobj.window);
	XCloseDisplay(xobj.display);	
	exit(0);		
      }
    }
  }

}
